package com.example.model;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    //创建数据源
    private static BasicDataSource bs;

    //获取连接
    public static Connection getConnection() {
        //创建连接对象
        Connection conn = null;
        //加载属性文件
        try {//创建属性集
//			Properties properties = new Properties();
//			InputStream resourceAsStream = JDBCUtil.class.getResourceAsStream("mysql.dbcp.properties");
//			properties.load(resourceAsStream);
//			bs = BasicDataSourceFactory.createDataSource(properties);
            Properties properties = new Properties();
            InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("/profile/mysql.dbcp.properties");
            properties.load(resourceAsStream);
            bs = BasicDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            conn = bs.getConnection();
            System.out.println(conn);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭操作
     */
    public static void closeAll(ResultSet set, PreparedStatement pst, Connection conn) {
        if (set != null) {

            try {
                set.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }


}
